{% extends "base.html" %}

{% set current_menu = 'lead' %}
{% set current_page = 'lead_pool' %}

{% block title %}线索管理 - 线索池{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('lead.lead_list') }}" class="text-gray-500 hover:text-gray-700">线索管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">线索池</li>
        </ol>
    </nav>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                    <i class="fas fa-users"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">未分配线索</p>
                    <p class="text-2xl font-semibold">{{ stats.unassigned }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-500">
                    <i class="fas fa-user-clock"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">今日新增</p>
                    <p class="text-2xl font-semibold">{{ stats.today_new }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-500">
                    <i class="fas fa-star"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">高优先级</p>
                    <p class="text-2xl font-semibold">{{ stats.high_priority }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-purple-100 text-purple-500">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">待分配3天以上</p>
                    <p class="text-2xl font-semibold">{{ stats.old_leads }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作区域 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <div class="flex items-center space-x-2 mb-4 md:mb-0">
                    <button id="batch-assign-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition disabled:bg-gray-400" disabled>
                        <i class="fas fa-user-plus mr-2"></i>批量分配
                    </button>
                    <button id="auto-assign-btn" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition">
                        <i class="fas fa-magic mr-2"></i>自动分配
                    </button>
                    <button class="px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">
                        <i class="fas fa-file-export mr-2"></i>导出
                    </button>
                </div>
                <div class="flex items-center space-x-2">
                    <div class="relative">
                        <input type="text" id="search" placeholder="搜索线索名称、公司、电话、邮箱..." 
                               class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ search }}">
                        <div class="absolute left-3 top-2.5 text-gray-400">
                            <i class="fas fa-search"></i>
                        </div>
                    </div>
                    <button id="search-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                        搜索
                    </button>
                </div>
            </div>
        </div>

        <!-- 筛选区域 -->
        <div class="p-4 border-b border-gray-200">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">线索来源</label>
                    <select id="source-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部来源</option>
                        {% for source in sources %}
                        <option value="{{ source }}" {% if source_filter == source %}selected{% endif %}>{{ source }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">优先级</label>
                    <select id="priority-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部优先级</option>
                        {% for priority in priorities %}
                        <option value="{{ priority }}" {% if priority_filter == priority %}selected{% endif %}">{{ priority }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                    <select id="time-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部时间</option>
                        <option value="today" {% if time_filter == 'today' %}selected{% endif %}>今天</option>
                        <option value="week" {% if time_filter == 'week' %}selected{% endif %}>本周</option>
                        <option value="month" {% if time_filter == 'month' %}selected{% endif %}>本月</option>
                        <option value="older" {% if time_filter == 'older' %}selected{% endif %}>更早</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">评分范围</label>
                    <select id="score-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部评分</option>
                        <option value="high" {% if score_filter == 'high' %}selected{% endif %}>高(70-100)</option>
                        <option value="medium" {% if score_filter == 'medium' %}selected{% endif %}>中(40-69)</option>
                        <option value="low" {% if score_filter == 'low' %}selected{% endif %}>低(0-39)</option>
                    </select>
                </div>
            </div>
            <div class="mt-4 flex justify-end">
                <button id="filter-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                    查询
                </button>
                <button id="reset-btn" class="ml-2 px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">
                    重置
                </button>
            </div>
        </div>

        <!-- 线索池列表表格 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="select-all" class="rounded border-gray-300 text-primary focus:ring-primary">
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            线索名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            公司名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            线索来源
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            优先级
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            评分
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            创建时间
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            待分配天数
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for lead in leads %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <input type="checkbox" class="lead-checkbox rounded border-gray-300 text-primary focus:ring-primary" value="{{ lead.id }}">
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div>
                                <div class="text-sm font-medium text-gray-900">
                                    <a href="{{ url_for('lead_pool_detail', lead_id=lead.id) }}" class="hover:text-primary">{{ lead.name }}</a>
                                </div>
                                <div class="text-sm text-gray-500">{{ lead.phone }}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ lead.company }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ lead.source }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                {% if lead.priority == '高' %}bg-red-100 text-red-800
                                {% elif lead.priority == '中' %}bg-yellow-100 text-yellow-800
                                {% elif lead.priority == '低' %}bg-green-100 text-green-800
                                {% else %}bg-gray-100 text-gray-800{% endif %}">
                                {{ lead.priority }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                {% if lead.score >= 70 %}bg-purple-100 text-purple-800
                                {% elif lead.score >= 40 %}bg-blue-100 text-blue-800
                                {% else %}bg-gray-100 text-gray-800{% endif %}">
                                {{ lead.score or '0' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ lead.created_at | format_time }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ lead.days_in_pool or '0' }} 天
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                <button class="assign-lead text-primary hover:text-blue-600" data-id="{{ lead.id }}" data-name="{{ lead.name }}">
                                    <i class="fas fa-user-plus" title="分配"></i>
                                </button>
                                <a href="{{ url_for('lead_pool_detail', lead_id=lead.id) }}" class="text-indigo-600 hover:text-indigo-900" title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="9" class="px-6 py-4 text-center text-sm text-gray-500">
                            暂无未分配的线索
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示 <span class="font-medium">{{ (page - 1) * per_page + 1 }}</span> 到 <span class="font-medium">{{ [page * per_page, stats.total]|min }}</span> 条，
                        共 <span class="font-medium">{{ stats.total }}</span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        {% if page > 1 %}
                        <a href="{{ url_for('lead.lead_pool', page=page-1, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">上一页</span>
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        {% else %}
                        <span class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-gray-100 text-sm font-medium text-gray-400">
                            <span class="sr-only">上一页</span>
                            <i class="fas fa-chevron-left"></i>
                        </span>
                        {% endif %}
                        
                        {% for p in range([1, page-2]|max, [total_pages+1, page+3]|min) %}
                        {% if p == page %}
                        <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">
                            {{ p }}
                        </span>
                        {% else %}
                        <a href="{{ url_for('lead.lead_pool', page=p, **request.args) }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                            {{ p }}
                        </a>
                        {% endif %}
                        {% endfor %}
                        
                        {% if page < total_pages %}
                        <a href="{{ url_for('lead.lead_pool', page=page+1, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">下一页</span>
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        {% else %}
                        <span class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-gray-100 text-sm font-medium text-gray-400">
                            <span class="sr-only">下一页</span>
                            <i class="fas fa-chevron-right"></i>
                        </span>
                        {% endif %}
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 分配线索模态框 -->
<div id="assign-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3 text-center">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-blue-100">
                <i class="fas fa-user-plus text-blue-600"></i>
            </div>
            <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">分配线索</h3>
            <div class="mt-2 px-7 py-3">
                <p class="text-sm text-gray-500">
                    将线索 "<span id="assign-lead-name"></span>" 分配给销售人员
                </p>
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">选择销售人员</label>
                    <select id="assign-user-id" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">请选择销售人员</option>
                        {% for user in sales_users %}
                        <option value="{{ user.id }}">{{ user.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="items-center px-4 py-3">
                <button type="button" id="cancel-assign" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                    取消
                </button>
                <button type="button" id="confirm-assign" class="px-4 py-2 bg-primary text-white text-base font-medium rounded-md w-24 hover:bg-blue-600">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 批量分配模态框 -->
<div id="batch-assign-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3 text-center">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-blue-100">
                <i class="fas fa-users text-blue-600"></i>
            </div>
            <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">批量分配线索</h3>
            <div class="mt-2 px-7 py-3">
                <p class="text-sm text-gray-500">
                    已选择 <span id="batch-count" class="font-semibold">0</span> 条线索进行分配
                </p>
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">选择销售人员</label>
                    <select id="batch-assign-user-id" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">请选择销售人员</option>
                        {% for user in sales_users %}
                        <option value="{{ user.id }}">{{ user.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">分配方式</label>
                    <div class="flex items-center">
                        <input type="radio" id="assign-all" name="assign-method" value="all" checked class="mr-2">
                        <label for="assign-all" class="text-sm text-gray-700">全部分配给同一人</label>
                    </div>
                    <div class="flex items-center mt-2">
                        <input type="radio" id="assign-distribute" name="assign-method" value="distribute" class="mr-2">
                        <label for="assign-distribute" class="text-sm text-gray-700">平均分配给所有销售人员</label>
                    </div>
                </div>
            </div>
            <div class="items-center px-4 py-3">
                <button type="button" id="cancel-batch-assign" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                    取消
                </button>
                <button type="button" id="confirm-batch-assign" class="px-4 py-2 bg-primary text-white text-base font-medium rounded-md w-24 hover:bg-blue-600">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
{{ super() }}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 搜索功能
        function initializeSearchButton() {
            const searchBtn = document.getElementById('search-btn');
            const searchInput = document.getElementById('search');
            
            if (searchBtn) {
                searchBtn.addEventListener('click', function() {
                    const searchValue = searchInput.value.trim();
                    const url = new URL(window.location.href);
                    if (searchValue) {
                        url.searchParams.set('search', searchValue);
                    } else {
                        url.searchParams.delete('search');
                    }
                    window.location.href = url.toString();
                });
            }
            
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        const searchValue = searchInput.value.trim();
                        const url = new URL(window.location.href);
                        if (searchValue) {
                            url.searchParams.set('search', searchValue);
                        } else {
                            url.searchParams.delete('search');
                        }
                        window.location.href = url.toString();
                    }
                });
            }
        }
        
        // 初始化搜索功能
        initializeSearchButton();
        
        // 筛选功能
        function initializeFilterButtons() {
            const filterBtn = document.getElementById('filter-btn');
            const resetBtn = document.getElementById('reset-btn');
            const sourceFilter = document.getElementById('source-filter');
            const priorityFilter = document.getElementById('priority-filter');
            const timeFilter = document.getElementById('time-filter');
            const scoreFilter = document.getElementById('score-filter');
            
            if (filterBtn) {
                filterBtn.addEventListener('click', function() {
                    const url = new URL(window.location.href);
                    
                    // 保留搜索参数
                    const searchValue = searchInput.value.trim();
                    if (searchValue) {
                        url.searchParams.set('search', searchValue);
                    } else {
                        url.searchParams.delete('search');
                    }
                    
                    // 设置筛选参数
                    if (sourceFilter.value) {
                        url.searchParams.set('source', sourceFilter.value);
                    } else {
                        url.searchParams.delete('source');
                    }
                    
                    if (priorityFilter.value) {
                        url.searchParams.set('priority', priorityFilter.value);
                    } else {
                        url.searchParams.delete('priority');
                    }
                    
                    if (timeFilter.value) {
                        url.searchParams.set('time', timeFilter.value);
                    } else {
                        url.searchParams.delete('time');
                    }
                    
                    if (scoreFilter.value) {
                        url.searchParams.set('score', scoreFilter.value);
                    } else {
                        url.searchParams.delete('score');
                    }
                    
                    window.location.href = url.toString();
                });
            }
            
            if (resetBtn) {
                resetBtn.addEventListener('click', function() {
                    // 重置所有筛选条件
                    sourceFilter.value = '';
                    priorityFilter.value = '';
                    timeFilter.value = '';
                    scoreFilter.value = '';
                    searchInput.value = '';
                    
                    // 跳转到基础URL
                    window.location.href = "{{ url_for('lead.lead_pool') }}";
                });
            }
        }
        
        // 初始化筛选功能
        initializeFilterButtons();
        
        // 全选功能
        function initializeSelectAll() {
            const selectAll = document.getElementById('select-all');
            const leadCheckboxes = document.querySelectorAll('.lead-checkbox');
            const batchAssignBtn = document.getElementById('batch-assign-btn');
            
            function updateBatchAssignButton() {
                const checkedBoxes = document.querySelectorAll('.lead-checkbox:checked');
                batchAssignBtn.disabled = checkedBoxes.length === 0;
            }
            
            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    leadCheckboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                    });
                    updateBatchAssignButton();
                });
            }
            
            leadCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateBatchAssignButton);
            });
        }
        
        // 初始化全选功能
        initializeSelectAll();
        
        // 单个分配功能
        const assignModal = document.getElementById('assign-modal');
        const assignLeadName = document.getElementById('assign-lead-name');
        const assignUserId = document.getElementById('assign-user-id');
        const cancelAssign = document.getElementById('cancel-assign');
        const confirmAssign = document.getElementById('confirm-assign');
        let currentLeadId = null;
        
        // 确保DOM加载完成后再绑定事件
        function initializeAssignButtons() {
            document.querySelectorAll('.assign-lead').forEach(button => {
                button.addEventListener('click', function() {
                    currentLeadId = this.getAttribute('data-id');
                    const leadName = this.getAttribute('data-name');
                    
                    assignLeadName.textContent = leadName;
                    assignUserId.value = '';
                    
                    assignModal.classList.remove('hidden');
                });
            });
        }
        
        // 初始化分配按钮
        initializeAssignButtons();
        
        // 取消单个分配
        function initializeCancelSingleAssign() {
            if (cancelAssign) {
                cancelAssign.addEventListener('click', function() {
                    assignModal.classList.add('hidden');
                    currentLeadId = null;
                });
            }
        }
        
        // 初始化取消单个分配按钮
        initializeCancelSingleAssign();
        
        // 确认单个分配
        function initializeConfirmSingleAssign() {
            if (confirmAssign) {
                confirmAssign.addEventListener('click', function() {
                    const userId = assignUserId.value;
                    
                    if (!userId) {
                        alert('请选择销售人员');
                        return;
                    }
                    
                    fetch(`/leads/${currentLeadId}/assign`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: `assigned_to=${userId}`
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('线索分配成功');
                            location.reload();
                        } else {
                            alert('线索分配失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('线索分配失败，请重试');
                    });
                });
            }
        }
        
        // 初始化确认单个分配按钮
        initializeConfirmSingleAssign();
        
        // 批量分配功能
        const batchAssignModal = document.getElementById('batch-assign-modal');
        const batchAssignBtn = document.getElementById('batch-assign-btn');
        const batchCount = document.getElementById('batch-count');
        const batchAssignUserId = document.getElementById('batch-assign-user-id');
        const cancelBatchAssign = document.getElementById('cancel-batch-assign');
        const confirmBatchAssign = document.getElementById('confirm-batch-assign');
        
        // 确保DOM加载完成后再绑定事件
        function initializeBatchAssignButton() {
            if (batchAssignBtn) {
                batchAssignBtn.addEventListener('click', function() {
                    const checkedBoxes = document.querySelectorAll('.lead-checkbox:checked');
                    batchCount.textContent = checkedBoxes.length;
                    batchAssignUserId.value = '';
                    
                    batchAssignModal.classList.remove('hidden');
                });
            }
        }
        
        // 初始化批量分配按钮
        initializeBatchAssignButton();
        
        // 取消批量分配
        function initializeCancelBatchAssign() {
            if (cancelBatchAssign) {
                cancelBatchAssign.addEventListener('click', function() {
                    batchAssignModal.classList.add('hidden');
                });
            }
        }
        
        // 初始化取消批量分配按钮
        initializeCancelBatchAssign();
        
        // 批量分配确认
        function initializeBatchAssignConfirm() {
            if (confirmBatchAssign) {
                confirmBatchAssign.addEventListener('click', function() {
                    const userId = batchAssignUserId.value;
                    const assignMethod = document.querySelector('input[name="assign-method"]:checked').value;
                    
                    if (assignMethod === 'all' && !userId) {
                        alert('请选择销售人员');
                        return;
                    }
                    
                    const checkedBoxes = document.querySelectorAll('.lead-checkbox:checked');
                    const leadIds = Array.from(checkedBoxes).map(box => box.value);
                    
                    // 发送批量分配请求
                    fetch('/api/lead_pool/batch_assign', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            lead_ids: leadIds,
                            user_id: userId,
                            method: assignMethod
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert(`成功分配 ${data.count} 条线索`);
                            location.reload();
                        } else {
                            alert('分配失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('分配失败，请重试');
                    });
                });
            }
        }
        
        // 初始化批量分配确认按钮
        initializeBatchAssignConfirm();
        
        // 自动分配功能
        const autoAssignBtn = document.getElementById('auto-assign-btn');
        
        // 确保DOM加载完成后再绑定事件
        function initializeAutoAssignButton() {
            if (autoAssignBtn) {
                autoAssignBtn.addEventListener('click', function() {
                    if (confirm('确定要自动分配所有未分配的线索吗？系统将根据负载均衡规则进行分配。')) {
                        fetch('/api/lead_pool/auto_assign', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert(`成功自动分配 ${data.count} 条线索`);
                                location.reload();
                            } else {
                                alert('自动分配失败: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('自动分配失败，请重试');
                        });
                    }
                });
            }
        }
        
        // 初始化自动分配按钮
        initializeAutoAssignButton();
        
        // 点击模态框外部关闭
        assignModal.addEventListener('click', function(e) {
            if (e.target === assignModal) {
                assignModal.classList.add('hidden');
                currentLeadId = null;
            }
        });
        
        batchAssignModal.addEventListener('click', function(e) {
            if (e.target === batchAssignModal) {
                batchAssignModal.classList.add('hidden');
            }
        });
    });
</script>
{% endblock %}